package ai.people.core.nebula.factory;

import ai.people.core.nebula.entity.NebulaTransaction;
import ai.people.core.nebula.holder.NebulaSessionContextHolder;
import ai.people.core.nebula.properties.ConnectProperties;
import com.vesoft.nebula.client.graph.net.NebulaPool;
import com.vesoft.nebula.client.graph.net.Session;
import com.vesoft.nebula.client.graph.net.SessionWrapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * nebula会话工厂bean
 *
 * @author yuanqinglong
 * @date 2022/5/11 11:07
 */
@Slf4j
public class NebulaSessionFactoryBean implements FactoryBean<SessionWrapper> {

    Logger logger = LoggerFactory.getLogger(NebulaSessionFactoryBean.class);

    /**
     * Nebula池
     */
    @Autowired(required = false)
    private NebulaPool nebulaPool;

    /**
     * 连接属性
     */
    @Autowired(required = false)
    private ConnectProperties connectProperties;


    public ConnectProperties getConnectProperties() {
        return connectProperties;
    }

    /**
     * 创建SessionWrapper
     *
     * @return {@link SessionWrapper}
     * @throws Exception 异常
     */
    @Override
    public SessionWrapper getObject() throws Exception {
        Session session = nebulaPool.getSession(connectProperties.getUsername(), connectProperties.getPassword(), true);
        NebulaSessionContextHolder.switchSpace(connectProperties.getSpaceName(), session);
        NebulaSessionContextHolder.setTx(NebulaTransaction.builder().session(session).build());
        logger.info("NebulaSessionFactoryBean create session completed {}", session);
        return new SessionWrapper(session);
    }

    /**
     * 返回SessionWrapper类型
     *
     * @return {@link Class}<{@link ?}>
     */
    @Override
    public Class<?> getObjectType() {
        return Session.class;
    }


    /**
     * 创建对象为原型Bean
     *
     * @return boolean
     */
    @Override
    public boolean isSingleton() {
        return false;
    }
}
